//
//  UUSettingsVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 24/01/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUSettingsVC.h"
#import "UUResourceManager.h"
#import "UULoginManager.h"
#import "AppDelegate.h"
#import <DKImagePickerController/DKImagePickerController-Swift.h>
#import <UUFoundation/DKImageCropEditViewController.h>
#import <UUFoundation/UUFileManager.h>
#import "UUUserManager.h"
#import "UUKeeperManager.h"
#import "UUVerifyCodeVC.h"

@interface UUSettingsVC ()

@property (nonatomic, weak) IBOutlet UILabel *versionLabel;
@property (nonatomic, weak) IBOutlet UIImageView *avatarImageView;
@property (nonatomic, weak) IBOutlet UIButton *logoutButton;

@end

@implementation UUSettingsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.backgroundColor = COMMON_BACKGROUND_COLOR;
    
    [self.logoutButton setTitleColor:COMMON_TEXT_ORANGE_COLOR forState:UIControlStateNormal];
    [self.logoutButton setBackgroundImage:GetResourceManager().buttonImage3 forState:UIControlStateNormal];
    [self.logoutButton setBackgroundImage:GetResourceManager().buttonImage3HL forState:UIControlStateHighlighted];
    
    self.avatarImageView.layer.cornerRadius = self.avatarImageView.width / 2;
    self.avatarImageView.layer.masksToBounds = YES;
    
    [self.avatarImageView uu_setImageWithURLString:GetUserManager().fetchUserInfo.avatar];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)logout:(id)sender {
    [UIAlertController presentAlertControllerWithTitle:@"确定退出登录？" message:nil doneBlock:^{
        POST_MSG(NOTIFICATION_USER_NEED_LOGOUT);
    } cancelBlock:nil];
}

- (void)updateAvatar {
    DKImagePickerController *pickerController = [DKImagePickerController new];
    pickerController.assetType = DKImagePickerControllerAssetTypeAllPhotos;
    pickerController.singleSelect = YES;
    [self presentViewController:pickerController animated:YES completion:nil];
    WEAK_SELF();
    pickerController.didSelectAssets = ^(NSArray<DKAsset *> *assets) {
        if ([assets count] == 0) {
            return;
        }
        
        [weakSelf pushToImageCropVC:assets.firstObject];
    };
}

- (void)requestVerifyCodeWithCompleteBlock:(void (^)(NSString *mobile, NSError *error))completeBlock {
    [GetKeeperManager() asyncSendUnbundingVerifyCodeWithCompleteBlock:^(NSString *mobile, NSError *error) {
        BLOCK_SAFE_CALLS(completeBlock, mobile, error);
    }];
}

- (NSString *)encryptMobile:(NSString *)mobile {
    return [mobile stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
}

- (void)deleteUser {
    UUUserInfo *userInfo = [GetUserManager() fetchUserInfo];
    if (userInfo.roleId == UUPermissionRoleTypeOwner) {
        [UIAlertController presentAlertControllerWithTitle:@"所有者不能被解绑!" message:nil doneBlock:nil];
        return;
    }
    
    [UIAlertController presentAlertControllerWithTitle:@"是否确认解绑?" message:nil doneBlock:^{
        ShowIndicatorInKeyWindow();
        WEAK_SELF();
        [self requestVerifyCodeWithCompleteBlock:^(NSString *mobile, NSError *error) {
            HideIndicatorInKeyWindow();
            
            if (error) {
                ShowTipsOnView(error.localizedDescription, weakSelf.view);
            } else {
                UUVerifyCodeVC *verifyCodeVC = [UUVerifyCodeVC instanceOfAppropriate];
                verifyCodeVC.mobile = [self encryptMobile:mobile];
                verifyCodeVC.codeDidInputCompleteBlock = ^(NSString *code) {
                    [GetKeeperManager() asyncDeleteKeeperWithKeeperId:GetUserManager().fetchUserInfo.userId
                                                           verifyCode:code
                                                        completeBlock:^(NSError *error) {
                                                            if (error == nil) {
                                                                POST_MSG(NOTIFICATION_USER_NEED_LOGOUT);
                                                            } else {
                                                                ShowTipsInKeyWindow(error.localizedDescription);
                                                            }
                                                        }];
                };
                verifyCodeVC.requestVerifyCodeBlock = ^(UUVerifyCodeRequestHanlder handler) {
                    [weakSelf requestVerifyCodeWithCompleteBlock:^(NSString *mobile, NSError *error) {
                        handler(error);
                    }];
                };
                
                [verifyCodeVC startCountdown];
                [self.navigationController pushViewController:verifyCodeVC animated:YES];
            }
        }];
    } cancelBlock:nil];
}

- (void)pushToImageCropVC:(DKAsset *)asset {
    ShowIndicatorInView(self.view);
    WEAK_SELF();
    [asset fetchFullScreenImageWithCompleteBlock:^(UIImage * _Nullable image, NSDictionary * _Nullable info) {
        if (image != nil) {
            DKImageCropEditViewController *vc = [[DKImageCropEditViewController alloc] init];
            vc.selectImage = image;
            [vc setCompleteBlock:^(UIImage *image) {
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
                [weakSelf uploadAvatar:image completeBlock:^(NSString *avatar, NSError *error) {
                    if (error == nil) {
                        [GetUserManager() asyncUpdateUserAvatar:avatar completeBlock:^(NSError *error) {
                            if (error == nil) {
                                HideIndicatorInView(weakSelf.view);
                                if (error == nil) {
                                    weakSelf.avatarImageView.image = image;
                                } else {
                                    ShowTipsOnView(error.localizedDescription, weakSelf.view);
                                }
                            } else {
                                ShowTipsOnView(error.localizedDescription, weakSelf.view);
                            }
                        }];
                    } else {
                        ShowTipsOnView(error.localizedDescription, weakSelf.view);
                    }
                }];
            }];
            [self presentViewController:vc animated:YES completion:nil];
        } else {
            ShowTipsOnView(@"获取图片失败", weakSelf.view);
        }
    }];
}

- (void)uploadAvatar:(UIImage *)image completeBlock:(void (^)(NSString *avatar, NSError *error))completeBlock {
    NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
    DKFileUploadBaseTask *task = [GetFileManager() uploadDataTask:imageData];
    [GetFileManager() startFileTask:task progressBlock:nil completeBlock:^(NSError *error) {
        [GetFileManager() writeCacheImageData:imageData key:task.storeKey];
        completeBlock(task.storeKey, error);
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row == 0) { // 修改头像
        [self updateAvatar];
    } else if (indexPath.row == 1) { // 解除绑定
        [self deleteUser];
    }
}

@end
